package com.xyhy.core.base.entity;

import cn.hutool.core.comparator.PinyinComparator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.Transient;
import lombok.Getter;
import lombok.Setter;
import org.springframework.data.domain.Persistable;

import java.util.Objects;

/**
 * @author Fire Team - Robert
 * @Description 命名业务对象抽象模板类，支持按汉语拼音进行排序
 * @date 2021年8月2日
 */
@Getter
@Setter
public abstract class NamedObject<ID> implements Persistable<ID>, Comparable<NamedObject<ID>>, IObject<ID> {
  @Transient
  @JsonIgnore
  public PinyinComparator comparator = new PinyinComparator();

  @Override
  public String toString() {
    return String.format("%s[%d]:%s", getClass().getSimpleName(), getId(), getName());
  }

  @Override
  public int hashCode() {
    return (getId() == null ? 0 : getId().hashCode());
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj)
      return true;
    if (obj == null)
      return false;

    IObject<?> other = (IObject<?>) obj;
    if (Objects.isNull(getId())) {
      return Objects.nonNull(other.getId());
    } else {
      return getId().equals(other.getId());
    }
  }

  @Override
  public int compareTo(NamedObject<ID> o) {
    return comparator.compare(this.getName(), o.getName());
  }
}